package com.suishoupai.xmb.service;

import com.suishoupai.xmb.exception.XmbException;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by caojian on 2017/4/20.
 */
@Service
public class HttpService {
    @Autowired
    private OkHttpClient okHttpClient;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Bean
    public OkHttpClient okHttpClient() {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(64);
        dispatcher.setMaxRequestsPerHost(16);
        ConnectionPool connectionPool = new ConnectionPool(32, 5, TimeUnit.MINUTES);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.dispatcher(dispatcher);
        builder.connectionPool(connectionPool);
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        return builder.build();
    }

    public String get(String url) throws XmbException {
        Request request = new Request.Builder().url(url).get().build();
        return this.synRequest(request);
    }

    public InputStream get8stream(String url) throws XmbException {
        Request request = new Request.Builder().url(url).get().build();
        OkHttpClient client = okHttpClient;
        try {
            okhttp3.Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().byteStream();
            } else {
                throw XmbException.newError("请求失败");
            }
        } catch (IOException e) {
            throw XmbException.newError("请求失败");
        }
    }

    public String post(String url, String json) throws XmbException {
        return this.post(url, json, null);
    }

    public String post(String url, String json, Map<String, String> headers) throws XmbException {
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request.Builder builder = new Request.Builder();
        builder.url(url).post(requestBody);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                builder.addHeader(key, value);
            }
        }
        Request request = builder.build();
        return this.synRequest(request);
    }

    //同步请求
    private String synRequest(Request request) throws XmbException {
        OkHttpClient client = okHttpClient;
        try {
            okhttp3.Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                return result;
            } else {
                throw XmbException.newError("请求失败");
            }
        } catch (IOException e) {
            throw XmbException.newError("请求失败");
        }
    }

}
